package apig.core;

import java.sql.*;
import java.util.*;

import org.h2.jdbcx.*;

import apig.algorithm.tokenizer.*;

/**
 * <b>Note:</b> Thread SAFE.
 * <p>
 * <b>Note:</b> Doesn't create threads.
 * 
 * @author Alex
 * 
 */
public class ServerThings {
	private static ServerThings things = null;

	public static synchronized ServerThings getThings() {
		if (things == null) {
			things = new ServerThings();
		}
		return things;
	}

	private final JdbcConnectionPool cp;

	public Connection getConnection() throws SQLException {
		boolean ok = false;
		Connection c = null;
		try {
			c = cp.getConnection();
			c.setAutoCommit(false);
			try (Statement st = c.createStatement()) {
				st.execute("set schema apig");
			}
			ok = true;
			return c;
		} finally {
			if (!ok)
				if (c != null)
					try {
						c.close();
					} catch (SQLException e) {
						e.printStackTrace();
					}
		}
	}

	public List<? extends Tokenizer> getTokenizers() {
		return Collections.unmodifiableList(Arrays.asList(new Tokenizer() {

			@Override
			public Token[] parse(String code) throws MalformedCodeException {
				return null;
			}
		}));
	}

	private ServerThings() {
		cp = JdbcConnectionPool.create("jdbc:h2:~/apigdb/apigdb;MVCC=TRUE",
				"sa", "");
		cp.setLoginTimeout(100000000);
		cp.setMaxConnections(1000);
		removeSessionData();
	}

	private void removeSessionData() {
		try (Connection c = getConnection(); Statement s = c.createStatement();) {
			s.executeUpdate("truncate table apig.user_session_data");
			c.commit();
		} catch (SQLException ex) {
			throw new RuntimeException(ex);
		}
	}

	void finish() {
		cp.dispose();
	}
}
